package com.tianya.dream.framework.web.service;

import com.tianya.common.web.constant.Constants;
import com.tianya.common.web.exception.CustomException;
import com.tianya.common.web.utils.StringUtils;
import com.tianya.plugtool.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @Description:
 * @version: 1.0.0
 * @author: tianya
 * @date: 2022-03-01
 */
@Component
public class VerifyCodeService {


    @Autowired
    private RedisCache redisCache;

    /** 默认的容错值. */
    public static float DEFAULT_TOLERANT = 0.1f;

    public Boolean verifyImageCode(String moveLength, String uuid) {
        String verifyKey = Constants.IMAGE_CODE_KEY + uuid;
        Double xWidth = redisCache.getCacheObject(verifyKey);
        return verifyImageCode(moveLength, uuid,xWidth);
    }
    public Boolean verifyImageCode(String moveLength, String uuid,Double xWidth) {
        Double dMoveLength = new BigDecimal(moveLength).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
        Boolean result = false;
        try {
            if (StringUtils.isEmpty(moveLength)) {
                throw new CustomException("移动距离不能为空");
            }
            if (StringUtils.isEmpty(uuid)) {
                throw new CustomException("验证码已失效");
            }
            if (null == xWidth) {
                throw new CustomException("图片验证过期，请重试");
            } else {
                // System.out.println(Math.abs(xWidth - dMoveLength));
                // 设置允许的偏差值
                if (Math.abs(xWidth - dMoveLength) > DEFAULT_TOLERANT) {
                    result = false;
                } else {
                    result = true;
                }
            }
        } catch (Exception e) {
            throw new CustomException("验证失败，请重试");
        }
        return result;
    }
}
